/*
 * @lc app=leetcode.cn id=2013 lang=typescript
 *
 * [2013] 检测正方形
 */

// @lc code=start
class DetectSquares {
  map: Map<number, Map<number, number>> = new Map();
  constructor() {}

  add(point: number[]): void {
    const [x, y] = point;
    if (!this.map.has(y)) {
      this.map.set(y, new Map<number, number>());
    }
    const yMap = this.map.get(y);
    yMap.set(x, (yMap.get(x) || 0) + 1);
  }

  count(point: number[]): number {
    const [x, y] = point;
    // 没有对应的y坐标，无法形成正方形
    if (!this.map.has(y)) return 0;

    const yMap = this.map.get(y);
    const entries = this.map.entries();
    let res = 0;
    // 枚举上下边的另一个y坐标
    for (const [col, cnt] of entries) {
      // 同一行，先跳过。下面会处理
      if (col === y) continue;
      const diff = col - y;
      // 由于会有重复的点，所有这里用乘法来计数
      res += (cnt.get(x) ?? 0) * (yMap.get(x + diff) ?? 0) * (cnt.get(x + diff) ?? 0);
      res += (cnt.get(x) ?? 0) * (yMap.get(x - diff) ?? 0) * (cnt.get(x - diff) ?? 0);
    }

    return res;
  }
}

/**
 * Your DetectSquares object will be instantiated and called as such:
 * var obj = new DetectSquares()
 * obj.add(point)
 * var param_2 = obj.count(point)
 */
// @lc code=end
